package com.yupi.usercenter.job;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.common.BaseResponse;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.ReactiveRedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class PreCacheJob {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
        @Autowired
        private UserService userService;
        @Autowired
        private RedissonClient redissonClient;

    @Scheduled(cron = "0 0 1 * * ?")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("yupao:redis:pricachejob");
        try {
            boolean b = lock.tryLock(0, -1, TimeUnit.MILLISECONDS);
            if (b){
                log.info("获取锁成功");
                // 1.查询最匹配的用户
                doCache();
            }
            if ( lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        } catch (InterruptedException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,e.getMessage());
        }finally {

        }



    }


    void doCache(){
        List<Long> mainUserIdList = Arrays.asList(609363l,609362l);
        for(Long loginUserId : mainUserIdList){

            String key= String.format("yupao:user:recommed:%d",loginUserId);
            // 2.写入缓存中
            Page<User> userPage = new Page<>(1,40);
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            Page<User> page = userService.page(userPage, userQueryWrapper);
            List<User> records = page.getRecords();
            List<User> collect = records.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());


            try {
                redisTemplate.opsForValue().set(key,page,60000, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                log.error("redis set key error",e);
            }

        }
    }
}
